# -*- coding:utf-8 -*-
# @Author:CL 1037654919@qq.com
# @Time : 2023/3/24 下午2:20
# @FileName: class_kuwo.py
# @Software: PyCharm


import requests
import time
import random
from utils import MongoDBUtil,mongo_manager
import math

MongoDBUtil = MongoDBUtil()
playlist =mongo_manager("playlist",db="kuwo")

from setting import language_dict,topic_dict,year_dict,style_dict,emotion_dict,scene_dict
def get_proxy():
    proxies = {
        'http': 'http://127.0.0.1:15732',
        'https': 'http://127.0.0.1:15732'
    }
    return proxies

class Kuwo():
    def __init__(self):
        # 默认的域名
        self.host = "http://www.kuwo.cn"
        # 根据关键字key获取歌曲的rid值的json数据的接口
        self.rid_url = "/api/www/search/searchMusicBykeyWord?key={}"
        # 根据rid获取歌曲下载链接的json数据的接口
        self.mp3_url = "/url?rid={}&type=convert_url3&br=128kmp3"
        # 获取音乐榜 可以得到sourceid
        self.bang_menu = "/api/www/bang/bang/bangMenu"
        # 获取精选歌单,可以得到歌单ID
        self.play_list = "/api/www/classify/playlist/getRcmPlayList?pn={}&rn={}&order=new&httpsStatus=1"
        # 获取歌手歌单,可以得到歌手音乐list
        self.artist_Music = "/api/www/artist/artistMusic?artistid={}&pn={}&rn=20&httpsStatus=1"
        # 获取分类歌单,可以得到歌单ID
        self.play_list_tag = "/api/www/classify/playlist/getTagPlayList?pn={}&rn={}&id={}&httpsStatus=1"
        # 获取歌单列表接口，可以得到歌单对应歌曲
        self.play_list_info = "/api/www/playlist/playListInfo?pid={}&pn={}&rn={}&httpsStatus=1"
        # 获取音乐信息的接口
        self.music_info = "/api/www/music/musicInfo?mid={}"
        # 根据 musicid 获取歌词信息
        self.song_lyric = "http://m.kuwo.cn/newh5/singles/songinfoandlrc?musicId={}"
        # 根据bangid 获取音乐列表
        self.music_list = "/api/www/bang/bang/musicList?bangId={}&pn={}&rn={}"
        # 一些必要的请求头
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36",
            "Referer": "https://www.kuwo.cn/playlists",  # 这个请求头没有的话，会出现 403 Forbidden
            "csrf": "YHQ83BQJIY",  # CSRF Token Not Found!
            "Cookie": "_ga=GA1.2.520024185.1679383881; Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1679383881; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1680074466; kw_token=YHQ83BQJIY",
        }

    def my_get(self, url, stream=False):
        """自定义的请求函数，可以打印一些信息，和处理反爬"""
        proxies = get_proxy() #代理
        response = requests.get(url, headers=self.headers,proxies=proxies, stream=stream)
        if response.status_code == 200:
            return response
        else:
            print('json get failed ,re try......')
            time.sleep(10)
            for __ in range(5):
                response = requests.get(url, headers=self.headers,proxies=proxies, stream=stream)
                if response.status_code == 200:
                    break
            return response

    def get_play_list(self, pn=1, rn=20):
        """
        获取歌单列表
        经过筛选后的数据格式
        {'img': 'https://img1.kuwo.cn/star/userpl2015/21/51/1626653888432_111259221_500.jpg',
         'uname': '凌MM120', 'lossless_mark': '0', 'favorcnt': '738', 'isnew': '',
         'extend': '', 'uid': '111259221', 'total': '29', 'commentcnt': '', 'imgscript': '',
         'digest': '8', 'name': '老歌是昨天的情书，余情未了', 'listencnt': '988723',
         'id': '3218156150', 'attribute': '', 'radio_id': '', 'desc': '', 'info': ''}],
          'rn': 30, 'pn': 1}
        """
        data= self.my_get(self.host + self.play_list.format(pn, rn))
        if data.status_code !=200:
            print('get data failed')
            return None
        return data.json()["data"]
    def get_play_list_tag(self, code,pn=1, rn=20):
        """
        获取歌单列表
        """
        data = self.my_get(self.host + self.play_list_tag.format(pn,rn,code))
        if data.status_code !=200:
            print('get data failed')
            return None
        return data.json()["data"]
    #获取歌单信息
    def get_play_list_info(self, id,pn=1, rn=20):
        # id = '3453950594'
        """
        获取歌单列表
        经过筛选后的数据格式
        {'img': 'https://img1.kuwo.cn/star/userpl2015/21/51/1626653888432_111259221_500.jpg',
         'uname': '凌MM120', 'lossless_mark': '0', 'favorcnt': '738', 'isnew': '',
         'extend': '', 'uid': '111259221', 'total': '29', 'commentcnt': '', 'imgscript': '',
         'digest': '8', 'name': '老歌是昨天的情书，余情未了', 'listencnt': '988723',
         'id': '3218156150', 'attribute': '', 'radio_id': '', 'desc': '', 'info': ''}],
          'rn': 30, 'pn': 1}
        """
        data = self.my_get(self.host + self.play_list_info.format(id,pn,rn))
        if data.status_code !=200:
            print('get data failed')
            return None
        return data.json()["data"]
        # return data.json()

    #获取歌曲信息,基于歌曲id
    def get_music_info(self, mid):
        # id = '238796500'
        """
        获取歌单列表
        经过筛选后的数据格式
        {'img': 'https://img1.kuwo.cn/star/userpl2015/21/51/1626653888432_111259221_500.jpg',
         'uname': '凌MM120', 'lossless_mark': '0', 'favorcnt': '738', 'isnew': '',
         'extend': '', 'uid': '111259221', 'total': '29', 'commentcnt': '', 'imgscript': '',
         'digest': '8', 'name': '老歌是昨天的情书，余情未了', 'listencnt': '988723',
         'id': '3218156150', 'attribute': '', 'radio_id': '', 'desc': '', 'info': ''}],
          'rn': 30, 'pn': 1}
        """
        data = self.my_get(self.host + self.music_info.format(mid))
        # print(data.json())
        if data.status_code !=200:
            print('get data failed')
            return None
        return data.json()["data"]
    # 获取歌词
    def get_song_lyric(self, mid):
        """
        根据 musicid 也就是 rid 获取歌词信息
        主要的接口数据:
        {"data":{"lrclist":[{"time":"0.0","lineLyric":"不分手的恋爱 - 汪苏泷"}, "songinfo":{}
        返回值 [(text, time)]
        """
        # time.sleep(random.randint(1, 2)) # 访问太快，会出现500的错误
        data = self.my_get(self.song_lyric.format(mid)).json()["data"]
        lrclist = []
        # {"data":null,"msg":"音乐查询失败","msgs":null,"profileid":"site","reqid":"081bc8bcXb67bX476aXa742X277424d2de4d","status":301}
        if data:
            lrclist = data["lrclist"] if data["lrclist"] else []
        lyric_filter = []
        for item in lrclist:
            lyric_filter.append((item["lineLyric"], int(float(item["time"])*1000)))
        return lyric_filter
    # 基于歌手id获取歌手音乐列表
    def get_artist_Music(self, artistid,pn=1):
        # id = '680' # 张杰
        """
       {musicrid: "MUSIC_207699170", barrage: "0", artist: "张杰",…}
        """
        data = self.my_get(self.host + self.artist_Music.format(artistid,pn))
        if data.status_code !=200:
            print('get data failed')
            return None
        return data.json()["data"]
    def get_bang(self, bangId,pn=1,rn=20):
        # bangId = '93' # 酷我飙升榜
        print(self.music_list.format(bangId,pn,rn))
        data = self.my_get(self.host + self.music_list.format(bangId,pn,rn))
        if data.status_code !=200:
            print('get data failed')
            return None
        return data.json()["data"]

if __name__ == "__main__":
    kuwo = Kuwo()
    # play_list = kuwo.get_play_list(1, 20)
    # print(play_list)
    # print(play_list['total'])
    # play_list_info = kuwo.get_play_list_info(3431253543,1, 20)
    # print(play_list_info)
    # print(type(play_list_info))


    from pprint import pprint
    data = kuwo.get_music_info(mid=47663979)
    pprint(data)
    pass

